<template>
  <j-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    switchFullscreen
    @ok="handleSubmit"
    @cancel="close"
    style="top:50px"
    cancelText="关闭">
    <a-card :bordered="false">
      <a-row :gutter="8">
        <a-col :span="6">
          <div>
<!--        <a-input-search v-model="searchValue"  style="margin-bottom: 8px" placeholder="Search" />-->
            <a-tree
              :auto-expand-parent="true"
              :tree-data="gData"
              :replaceFields="replaceFields"
              @select="onSelect"
              :autoExpandParent="true"
              :defaultExpandAll="true"
            >
              <template #title="{ name }">
<!--                <span>{{name}}</span>-->
                <span v-if="name.indexOf(searchValue) > -1">
                  {{ name.substr(0, title.indexOf(searchValue)) }}
                  <span style="color: #f50">{{ searchValue }}</span>
                  {{ name.substr(title.indexOf(searchValue) + searchValue.length) }}
                </span>
                <span v-else>{{ name }}</span>
              </template>
            </a-tree>
          </div>
        </a-col>
        <a-col :span="18">
          <!-- 查询区域 -->
          <div class="table-page-search-wrapper">
              <tsl-simple-query :data-source="dataSource" :columns="columns"  @searchQueryTab="searchQueryTab"
                                @clearQueryTab="clearQueryTab" @initQueryColumns="initQueryColumns" :ignoreColumns="ignoreColumns"
                                ></tsl-simple-query>
          </div>
          <!-- 查询区域-END -->
          <!-- table区域-begin -->
          <div>
            <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
              <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a
              style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
              <a style="margin-left: 24px" @click="onClearSelected">清空</a>
            </div>
            <a-table
              ref="table"
              size="middle"
              :scroll="{x:true}"
              bordered
              :rowKey="(record,index)=>{return record.id}"
              :columns="columns"
              :dataSource="dataSource"
              :pagination="ipagination"
              :loading="loading"
              :rowSelection="{selectedRowKeys: selectedRowKeys , onChange: onSelectChange, type: checkval,onSelect: onSelectRow}"
              class="j-table-force-nowrap"
              @change="handleTableChange"
              :style="{height: '300px'}"

            >
              <template slot='htmlSlot' slot-scope='text'>
                <div v-html='text'></div>
              </template>
            </a-table>
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="8">
        <a-col :span="24">
          <a-table
            ref="table1"
            size="middle"
            :scroll="{x:true}"
            bordered
            :rowKey="(record,index)=>{return record.id}"
            :columns="columns"
            :dataSource="checkSelectRows"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange , type: checkval}"
            class="j-table-force-nowrap">
            <template slot='htmlSlot' slot-scope='text'>
              <div v-html='text'></div>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </a-card>

  </j-modal>
</template>
<script>
import '@/assets/less/TableExpand.less'
import {mixinDevice} from '@/utils/mixin'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import { getAction } from '@api/manage'
import TslSimpleQuery from '@comp/tsl/TslSimpleQuery.vue'

export default {
  name: 'ErpGoodsListModel',
  mixins: [JeecgListMixin, mixinDevice],
  components: {TslSimpleQuery},
  // props: ['category', "modalWidth",],
  props: {
    category: {
      type: Number,
      required: false,
      default: 4
    },
    modalWidth: {
      type: Number,
      required: false,
      default: 1250
    },
    checkval: {
      type: String,
      default: 'radio'
    },
    supplierId: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      gData:[
        {key:'1',title:"1",children:[{key:'1-1',title:"1-1"}]}
      ],
      replaceFields:{
        children:'children', title:'name', key:'code'
      },
      selectCategory: '',
      searchValue: '',
      description: '物料基础信息管理页面',
      visible: false,
      title: '选择物料',
      disableMixinCreated: true,
      isOpenSettingColumns: false,
      queryParam: {categoryCode: this.category},
      checkSelectRows: [],
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '编号',
          align: "center",
          dataIndex: 'code'
        },
        {
          title: '名称',
          align: "center",
          dataIndex: 'name'
        },
        {
          title: '规格',
          align: "center",
          dataIndex: 'noneSpec'
        },
        {
          title: '包装规格(g)',
          align: "center",
          dataIndex: 'packSpec'
        },
        {
          title: '物料种类',
          align: "center",
          dataIndex: 'categoryCodeText'
        },
        {
          title: '客户物料编号',
          align: "center",
          dataIndex: 'customCode'
        },
        {
          title: '计量单位',
          align: "center",
          dataIndex: 'meUnit_dictText'
        },
        {
          title: '辅助单位',
          align: "center",
          dataIndex: 'auUnit_dictText'
        },
        // {
        //   title: '供应商',
        //   align: "center",
        //   dataIndex: 'supplierName'
        // },
        {
          title: '状态',
          align: "center",
          dataIndex: 'status_dictText'
        },
        {
          title: '换算率',
          align: "center",
          dataIndex: 'coRate'
        },
        {
          title: '物料分类',
          align: "center",
          dataIndex: 'classificationId_dictText'
        },
        {
          title: '是否有版样',
          align: "center",
          dataIndex: 'isPattern_dictText'
        },
        {
          title: '安全库量',
          align: "center",
          dataIndex: 'stockQuantity'
        },
        {
          title: '所属仓库',
          align: "center",
          dataIndex: 'warehouseCodeText'
        },
        {
          title: '是否关联包材',
          align: "center",
          dataIndex: 'isAssBc_dictText'
        },
        {
          title: '是否公用',
          align: "center",
          dataIndex: 'isPublic_dictText'
        },
        {
          title: '是否领料',
          align: "center",
          dataIndex: 'isUse_dictText'
        },
        {
          title: '备注',
          align: "center",
          dataIndex: 'remark'
        }
      ],
      url: {
        list: "/base/erpGoods/list",
        delete: "/base/erpGoods/delete",
        deleteBatch: "/base/erpGoods/deleteBatch",
        exportXlsUrl: "/base/erpGoods/exportXls",
        importExcelUrl: "base/erpGoods/importExcel",
      },
      dictOptions: {},
      superFieldList: [],
      ignoreColumns: ["id"]
    }
  },
  created() {
    this.getSuperFieldList();
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
  watch:{
    category(newval,oldval){
      this.loadGoodsCategory();
    }
  },
  mounted() {
    this.loadGoodsCategory();
  },
  methods: {
    loadGoodsCategory(){
      // 加载分类
      getAction('/goods/erpGoodsCategory/categorylist',{ category: this.category}).then(res=>{
        if(res.success){
          this.gData = res.result
        }
      })
    },
    onSelectRow(record, selected, selectedRows, nativeEvent){
      if(selected){
        this.dataSourceBack.forEach(item=>{
          if(item.id == record.id){
            this.checkSelectRows.push(item);
          }
        })
      }else{
        // this.selectedRowKeys = this.selectedRowKeys.filter(item => item !== record.id);
        this.checkSelectRows = this.checkSelectRows.filter(item => item.id != record.id);
      }
    },
    onSelect(selectedKeys, e){
      this.selectCategory =  selectedKeys[0]
      // this.queryParam = { categoryCode: selectedKeys[0] }
      this.loadData();
    },
    handleSubmit() {
      this.getGoodsSelectRows();
      // this.searchReset(false)
      this.queryParam = {};
      this.onClearSelected();
      this.close();
    },
    add() {
      this.showModal();
    },
    showModal() {
      this.dataSource = []
      this.visible = true;
      this.loadData();
    },
    getGoodsSelectRows() {
      let selectedRow = null;
      if(this.checkval=='radio'){
         selectedRow = this.selectionRows[0];
      }else{
         selectedRow = this.selectionRows
      }
      //传递选中的数据
      this.$emit("handlerOk", this.checkSelectRows);
      this.checkSelectRows = []
      this.selectionRows = []
      this.selectedRowKeys = []
      this.queryParam = {}
    },
    initDictConfig() {
    },
    close() {
      this.queryParam = {}
      this.checkSelectRows = []
      this.selectionRows = []
      this.selectedRowKeys = []
      this.visible = false;
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({type: 'string', value: 'code', text: '编号', dictCode: ''})
      fieldList.push({type: 'string', value: 'name', text: '名称', dictCode: ''})
      fieldList.push({type: 'string', value: 'noneSpec', text: '规格', dictCode: ''})
      fieldList.push({type: 'int', value: 'packSpec', text: '包装规格(g)', dictCode: ''})
      fieldList.push({type: 'sel_user', value: 'categoryCode', text: '物料种类'})
      fieldList.push({type: 'string', value: 'customCode', text: '客户物料编号', dictCode: ''})
      fieldList.push({type: 'string', value: 'meUnit', text: '计量单位', dictCode: 'ji_unit'})
      fieldList.push({type: 'string', value: 'auUnit', text: '辅助单位', dictCode: 'zl_unit'})
      fieldList.push({type: 'int', value: 'status', text: '状态', dictCode: 'erp_status'})
      fieldList.push({type: 'string', value: 'coRate', text: '换算率', dictCode: ''})
      fieldList.push({
        type: 'string',
        value: 'classificationId',
        text: '物料分类',
        dictCode: "erp_goods_classification,name,id"
      })
      fieldList.push({type: 'int', value: 'isPattern', text: '是否有版样', dictCode: 'is_open'})
      fieldList.push({type: 'int', value: 'stockQuantity', text: '安全库量', dictCode: ''})
      fieldList.push({type: 'sel_user', value: 'warehouseCode', text: '所属仓库'})
      fieldList.push({type: 'int', value: 'isAssBc', text: '是否关联包材', dictCode: 'is_open'})
      fieldList.push({type: 'int', value: 'isPublic', text: '是否公用', dictCode: 'is_open'})
      fieldList.push({type: 'string', value: 'isUse', text: '是否领料', dictCode: 'is_open'})
      fieldList.push({type: 'string', value: 'remark', text: '备注', dictCode: ''})
      this.superFieldList = fieldList
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      if(this.supplierId){
        params.supplierId = this.supplierId;
      }
      if(this.category){
        params.categoryCode = this.category
      }
      if(this.selectCategory){
        params.categoryCode = this.selectCategory
      }

      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          this.dataSource = res.result.records || res.result;
          this.dataSourceBack = this.dataSource
          if (res.result.total) {
            this.ipagination.total = res.result.total;
          } else {
            this.ipagination.total = 0;
          }
          //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.loading = false
      })
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>